package site.immonkey.ftptest.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.function.Consumer;

public class IOUtils {
	private static final int BUFFER_SIZE = 1024 * 512; 

	public static String getSocketContent(Socket socket, String encode) throws IOException {
		InputStream in = socket.getInputStream();
		StringBuilder sb = new StringBuilder();
		byte[] data = new byte[BUFFER_SIZE];
		int len = 0;
		while ((len = in.read(data, 0, data.length)) != -1) {
			sb.append(new String(data, 0, len, encode));
		}
		return sb.toString();
	}

	public static void saveStreamToFile(Socket socket, String filePath, Consumer<Long> listen) throws IOException {
		File file = new File(filePath);
		if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
		InputStream in = socket.getInputStream();
		OutputStream out = new FileOutputStream(file);
		copyStream(in, out, listen);
		out.close();
	}

	public static final void copyStream(InputStream in, OutputStream out, Consumer<Long> listen) throws IOException {
		long schedule = 0;
		byte[] data = new byte[BUFFER_SIZE];
		int len = 0;
		while ((len = in.read(data, 0, data.length)) != -1) {
			out.write(data, 0, len);
			if (listen != null) listen.accept(schedule += len);
		}
		out.flush();
	}
}
